package com.ouroboroswiki.core.content;

import java.util.ArrayList;
import java.util.Map;

import com.ouroboroswiki.core.AbstractContentRepositoryProxy;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentRepository;
import com.ouroboroswiki.core.ContentUtil;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class AggregatePathStepContentRepositoryProxy extends
		AbstractContentRepositoryProxy {

	public AggregatePathStepContentRepositoryProxy( ContentRepository proxied ) {
		this.proxied = proxied;
	}
	
	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		return proxied.buildVersion(principal, getAggregatePath(path), versionPath, versionBuilder);
	}

	@Override
	public boolean exists(Object principal, ContentPath path)
			throws ContentException {
		return proxied.exists(principal, getAggregatePath(path));
	}

	@Override
	public Content getContent(Object principal, ContentPath path, Version version,
			Map<String, Object> properties) throws ContentException {
		return proxied.getContent(principal, getAggregatePath(path), version, properties);
	}

	private ContentPath getAggregatePath( ContentPath path ) {
		ArrayList<ContentPath> splits = ContentUtil.split(path);
		for( int i=splits.size(); i>0; ) {
			i--;
			StringBuffer sb = new StringBuffer();
			ContentPath p = splits.get(i);
			ArrayList<ContentPath> paths = new ArrayList<ContentPath>();
			while( p != null ) {
				sb.append(p.getName());
				paths.add( p );
				p = p.getOnlyChild();
				if( p != null ) {
					sb.append('/');
				}
			}
			ContentPath previous = null;
			for( int j=paths.size(); j>0; ) {
				j--;
				ContentPath o = paths.get( j );
				String name;
				if( j == paths.size()-1 ) {
					name = sb.toString();
				} else {
					name = o.getName();
				}
				previous = new ContentPath( name, previous, o.isContextualBreak() );
			}

			splits.set(i, previous);
		}
		return ContentUtil.mergeToPath(splits);
	}
}
